package lab3;

import java.util.Random;

public class BinaryOperation {
    private int leftOperand;
    private int rightOperand;
    private char operator;
    private int value;
    private static final int UPPER = 100;
    private static final int LOWER = 0;
    private static Random random = new Random();
    
    // 默认构造器
    public BinaryOperation() {}
    
    // 带参数构造器
    public BinaryOperation(int left, int right, char op) {
        construct(left, right, op);
    }
    
    // 构造方法
    private void construct(int left, int right, char op) {
        leftOperand = left;
        rightOperand = right;
        operator = op;
        if (op == '+') {
            value = left + right;
        } else {
            value = left - right;
        }
    }
    
    // 访问器方法
    public int getLeftOperand() {
        return leftOperand;
    }
    
    public int getRightOperand() {
        return rightOperand;
    }
    
    public char getOperator() {
        return operator;
    }
    
    public int getValue() {
        return value;
    }
    
    // 生成加法算式
    public BinaryOperation generateAdditionOperation() {
        int left, right, result;
        left = random.nextInt(UPPER + 1);
        do {
            right = random.nextInt(UPPER + 1);
            result = left + right;
        } while (result > UPPER);
        
        BinaryOperation bop = new BinaryOperation();
        bop.construct(left, right, '+');
        return bop;
    }
    
    // 生成减法算式
    public BinaryOperation generateSubstractOperation() {
        int left, right, result;
        left = random.nextInt(UPPER + 1);
        do {
            right = random.nextInt(UPPER + 1);
            result = left - right;
        } while (result < LOWER);
        
        BinaryOperation bop = new BinaryOperation();
        bop.construct(left, right, '-');
        return bop;
    }
    
    // 随机生成加法或减法算式
    public BinaryOperation generateBinaryOperation() {
        if (random.nextBoolean()) {
            return generateAdditionOperation();
        } else {
            return generateSubstractOperation();
        }
    }
    
    // 重写equals方法
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        
        BinaryOperation that = (BinaryOperation) obj;
        return leftOperand == that.leftOperand &&
               rightOperand == that.rightOperand &&
               operator == that.operator;
    }
    
    // 字符串表示
    @Override
    public String toString() {
        return leftOperand + "" + operator + "" + rightOperand;
    }
    
    public String asString() {
        return toString();
    }
    
    public String fullString() {
        return toString() + "=" + value;
    }
}